<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager;

use app\common\model\Level;
use app\common\model\Merchant;
use app\common\model\Platform\Log;
use app\common\model\ProfitStatistics;
use app\common\model\Proxy;
use app\common\model\Rebate;
use app\common\model\Store;
use app\common\model\Team;
use app\common\model\User;
use app\common\model\UserTeam;
use app\common\model\WriteOff;
use think\Db;
use think\Exception;

class RebateManager extends BaseManager
{


    /**
     *
     * @param User $user
     * @param int $type
     * @param bool $trans
     * @return array
     */
    public static function Rebate(User $user,int $type,int $id,bool $trans=true):array
    {
        if ($trans){
            Db::startTrans();
        }
        $userId  = $user->id;
        try {
            $info = Team::where('t_id',$id)->find();
            if (!$info){
                throw new Exception('当前组队信息不存在');
            }

            $result = EmployeeManager::authCheck($userId,$info['store_id'],$info['is_store'],$info,EmployeeManager::TYPE_GROUP);
            if ($result['code'] != EmployeeManager::$successCode){
                throw new Exception($result['message']);
            }

            if ($info['confirm'] == Team::CONFIRM_YES){
                throw new Exception('当前数据已返点，无法再次返点');
            }

            if ($info['end_date'] > time()){
                throw new Exception('当前组队未结束，请结束后再操作');
            }

            if ($info['is_store'] != Team::IS_STORE_YES){
                // 如果不是门店组队，则需要自动核销队长订单信息
                $userTeamInfo  = UserTeam::where('team',$info['t_id'])->where('user_id',$userId)->where('state',UserTeam::STATE_SUCCESS)->where('pay_state',UserTeam::PAY_STATUS_SUCCESS)->find();
                if(!$offInfo = WriteOff::create([
                    'type'=> WriteOff::TYPE_TEAM,
                    'writer'=>$userId,
                    'user_id'=>$userId,
                    'relation_id'=>$userTeamInfo['ut_id'],
                    'create_time'=>time(),
                ])){
                    throw new Exception('当前核销记录插入失败');
                }

                $userTeamInfo->state = UserTeam::STATE_WRITE_OFF;
                $userTeamInfo->up_date = time();
                $userTeamInfo->write_off_id = $offInfo->id;
                $userTeamInfo->save();
            }

            $result = self::RebateStatistics($info,false);
            if ($result['code'] != self::$successCode){
                throw new Exception($result['message']);
            }

            $info->confirm  = Team::CONFIRM_YES;
            $info->save();
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans){
                Db::rollback();
            }
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage()];
    }

    /*public static function RebateStatistics(Team $info,$trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {
            $consumeTotal = 0;
            $userTeamModel = new UserTeam();
            $userTeamInfo = $userTeamModel->alias('ut')
                ->join('order o','ut.order_id = o.po_id','inner')
                ->where('ut.team',$info['t_id'])
                ->where('ut.state',UserTeam::STATE_WRITE_OFF)
                ->field('ut.user_id,ut.ut_id,ut.team,ut.state,ut.pay_state,ut.order_id,po.order_money,po.pref_money,po.user_coupon_id,po.real_money')
                ->select();
            //$userTeamInfo = UserTeam::where('team',$info['t_id'])->where('state',UserTeam::STATE_WRITE_OFF)->select();
            $userTeamCount = count($userTeamInfo);
            $level = Level::where('vl_id',$info['level'])->find();
            $date = time();
            if ($info['is_store'] == Team::IS_STORE_YES){
                $store_rebate = bcadd($level['store_rebate'],0,2);
                $storeMoney = bcdiv(bcmul(bcmul($info['cost'],$userTeamCount,2),$store_rebate,2),100,2);
                $consumeTotal = bcadd($consumeTotal,$storeMoney,2);
                $insertData  = [
                    'user_id'=>$info['captain'],
                    'store_id'=>$info['store_id'],
                    'type'=>Rebate::TYPE_TEAM,
                    'relation_id'=>$info['t_id'],
                    'rebate_rate'=>$store_rebate,
                    'rebate_money'=>$storeMoney,
                    'rebate_date'=>$date,
                    'rebate_cost'=>$info['cost'],
                    'number'=>$userTeamCount,
                    'create_time'=>$date,
                    'update_time'=>$date
                ];

                if(!Rebate::create($insertData)){
                    throw new Exception('确认失败');
                }

                $merchantId = Store::where('id',$info['store_id'])->value('merchant_id');
                $result = StoreAccountManager::money($merchantId,$info['store_id'],$storeMoney,StoreAccountManager::CHANGE_TYPE_INCOME,$date,StoreAccountManager::TYPE_TEAM,[],false);
                if ($result['code']!=StoreAccountManager::$successCode){
                    throw new Exception($result['message']);
                }

                $statisticsResult = StatisticsManager::enter($merchantId,$info['store_id'],$storeMoney,time(),ProfitStatistics::TYPE_TEAM,StatisticsManager::TYPE_PROFIT);
                if ($statisticsResult['code']!=StatisticsManager::$successCode){
                    throw new Exception($statisticsResult['message']);
                }

                $merchantUserId = Merchant::where('id',$merchantId)->value('user_id');
                if ($merchantUserId){
                    $invited_user_id = User::where('id',$merchantUserId)->value('invited_user_id');
                    if ($invited_user_id && $storeMoney){
                        $proxyInfo = Proxy::where('user_id',$invited_user_id)->find();
                        if ($proxyInfo){
                            $proxyRate = bcadd($level['proxy_rebate'],0,2);
                            $proxyMoney = bcdiv(bcmul($storeMoney,$proxyRate,2),100,2);

                            $consumeTotal = bcadd($consumeTotal,$proxyMoney,2);
                            $insertData  = [
                                'user_id'=>$invited_user_id,
                                'store_id'=>$info['store_id'],
                                'type'=>Rebate::TYPE_TEAM,
                                'relation_id'=>$info['t_id'],
                                'rebate_rate'=>$proxyRate,
                                'rebate_money'=>$proxyMoney,
                                'rebate_date'=>$date,
                                'rebate_cost'=>$info['cost'],
                                'number'=>$userTeamCount,
                                'create_time'=>$date,
                                'update_time'=>$date
                            ];

                            if(!Rebate::create($insertData)){
                                throw new Exception('确认失败');
                            }

                            $result = UserAccountManager::money($invited_user_id,$proxyMoney,UserAccountManager::CHANGE_TYPE_INCOME,$date,UserAccountManager::TYPE_PROXY_STORE_TEAM_REWARD,['relation_id'=>$info['t_id']],false);
                            if ($result['code']!=UserAccountManager::$successCode){
                                throw new Exception($result['message']);
                            }

                            $resultPlatform = PlatformManager::platformLog($proxyMoney,date('Y-m-d H:i:s',$date),Log::DIRECTIVE_OUT,Log::TYPE_PROXY_STORE_TEAM_REWARD,['recipient'=>$proxyInfo['user_id']],false);
                            if ($resultPlatform['code']!=PlatformManager::$successCode){
                                throw new Exception($resultPlatform['message']);
                            }

                            $resultProxy = ProxyManager::Statistics($proxyMoney,date('Y-m-d H:i:s',$date),$proxyInfo['user_id'],$proxyInfo['id'],false);
                            if ($resultProxy['code']!=ProxyManager::$successCode){
                                throw new Exception($resultProxy['message']);
                            }
                        }
                    }
                }

            }else{
                $captain_rebate = $level['captain_rebate'];
                $money = bcdiv(bcmul(bcmul($info['cost'],$userTeamCount,2),$captain_rebate,2),100,2);
                $consumeTotal = bcadd($consumeTotal,$money,2);
                $insertData  = [
                    'user_id'=>$info['captain'],
                    'store_id'=>$info['store_id'],
                    'type'=>Rebate::TYPE_TEAM,
                    'relation_id'=>$info['t_id'],
                    'rebate_rate'=>$captain_rebate,
                    'rebate_money'=>$money,
                    'rebate_date'=>$date,
                    'rebate_cost'=>$info['cost'],
                    'number'=>$userTeamCount,
                    'create_time'=>$date,
                    'update_time'=>$date
                ];

                if(!Rebate::create($insertData)){
                    throw new Exception('确认失败');
                }

                $result = UserAccountManager::money($info['captain'],$money,UserAccountManager::CHANGE_TYPE_INCOME,$date,UserAccountManager::TYPE_TEAM,[$info['t_id']],false);
                if ($result['code']!=UserAccountManager::$successCode){
                    throw new Exception($result['message']);
                }
            }
            foreach ($userTeamInfo as $k=>$v){
                if ($v->user_coupon_id == 0){
                    $v_invited_user_id = User::where('id',$v->user_id)->value('invited_user_id');
                    if ($v_invited_user_id){
                        $v_proxyInfo = Proxy::where('user_id',$v_invited_user_id)->find();
                        if ($v_proxyInfo){
                            $v_proxyRate = bcadd($level['proxy_rebate'],0,2);
                            $v_proxyMoney = bcdiv(bcmul($info['cost'],$v_proxyRate,2),100,2);
                            $insertData  = [
                                'user_id'=>$v->user_id,
                                'store_id'=>$info['store_id'],
                                'type'=>Rebate::TYPE_TEAM,
                                'relation_id'=>$info['t_id'],
                                'rebate_rate'=>$v_proxyRate,
                                'rebate_money'=>$v_proxyMoney,
                                'rebate_date'=>$date,
                                'rebate_cost'=>$info['cost'],
                                'number'=>1,
                                'create_time'=>$date,
                                'update_time'=>$date
                            ];

                            if(!Rebate::create($insertData)){
                                throw new Exception('确认失败');
                            }
                            $consumeTotal = bcadd($consumeTotal,$v_proxyMoney,2);
                            $result = UserAccountManager::money($v_invited_user_id,$v_proxyMoney,UserAccountManager::CHANGE_TYPE_INCOME,$date,UserAccountManager::TYPE_PROXY_CAPTAIN_TEAM_REWARD,['relation_id'=>$v->team,'relation_order'=>$v->order_id],false);
                            if ($result['code']!=UserAccountManager::$successCode){
                                throw new Exception($result['message']);
                            }

                            $resultPlatform = PlatformManager::platformLog($v_proxyMoney,date('Y-m-d H:i:s',$date),Log::DIRECTIVE_OUT,Log::TYPE_PROXY_CAPTAIN_TEAM_REWARD,['recipient'=>$v_proxyInfo['user_id'],'relation_id'=>$v->team,'relation_order'=>$v->order_id],false);
                            if ($resultPlatform['code']!=PlatformManager::$successCode){
                                throw new Exception($resultPlatform['message']);
                            }

                            $resultProxy = ProxyManager::Statistics($v_proxyMoney,date('Y-m-d H:i:s',$date),$v_proxyInfo['user_id'],$v_proxyInfo['id'],false);
                            if ($resultProxy['code']!=ProxyManager::$successCode){
                                throw new Exception($resultProxy['message']);
                            }
                        }
                    }
                }

            }

            if ($consumeTotal){
                $surplusAmount = bcsub(bcmul($info['cost'],$info['number_people'],2),$consumeTotal,2);
                if ($surplusAmount){
                    $resultPlatform = PlatformManager::platformLog($surplusAmount,date('Y-m-d H:i:s',$date),Log::DIRECTIVE_INCOME,Log::TYPE_TEAM,[],false);
                    if ($resultPlatform['code']!=PlatformManager::$successCode){
                        throw new Exception($resultPlatform['message']);
                    }
                }
            }
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans){
                Db::rollback();
            }
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage()];


    }*/


    public static function RebateStatistics(Team $info,$trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {
            $consumeTotal = 0;
            $userTeamModel = new UserTeam();
            $totalMoney = $userTeamModel->alias('ut')
                ->join('order o','ut.order_id = o.po_id','inner')
                ->where('ut.team',$info['t_id'])
                ->where('ut.state','in',[UserTeam::STATE_SUCCESS,UserTeam::STATE_WRITE_OFF])
                ->sum('o.real_money');

            $storeWhereMoney = $userTeamModel->alias('ut')
                ->join('order o','ut.order_id = o.po_id','inner')
                ->where('ut.team',$info['t_id'])
                ->where('ut.state',UserTeam::STATE_WRITE_OFF)
                ->sum('o.real_money');

            $storeWhereCount = $userTeamModel->alias('ut')
                ->join('order o','ut.order_id = o.po_id','inner')
                ->where('ut.team',$info['t_id'])
                ->where('ut.state',UserTeam::STATE_WRITE_OFF)
                ->count();

            $proxyWhereMoney = $userTeamModel->alias('ut')
                ->join('order o','ut.order_id = o.po_id','inner')
                ->where('ut.team',$info['t_id'])
                ->where('ut.state',UserTeam::STATE_WRITE_OFF)
                ->where('o.user_coupon_id',0)
                ->sum('o.real_money');

            $proxyWhereCount = $userTeamModel->alias('ut')
                ->join('order o','ut.order_id = o.po_id','inner')
                ->where('ut.team',$info['t_id'])
                ->where('ut.state',UserTeam::STATE_WRITE_OFF)
                ->where('o.user_coupon_id',0)
                ->sum('o.real_money');
            $level = Level::where('vl_id',$info['level'])->find();
            $date = time();
            if ($info['is_store'] == Team::IS_STORE_YES){


                $storeInfo = Store::where('id',$info['store_id'])->find();
                $store_rebate = $storeInfo['rate'] > 0 ? bcadd($storeInfo['rate'],0,2) : bcadd($level['store_rebate'],0,2);
                $storeMoney = bcdiv(bcmul($storeWhereMoney,$store_rebate,2),100,2);
                $consumeTotal = bcadd($consumeTotal,$storeMoney,2);
                $insertData  = [
                    'user_id'=>$info['captain'],
                    'store_id'=>$info['store_id'],
                    'type'=>Rebate::TYPE_TEAM,
                    'relation_id'=>$info['t_id'],
                    'rebate_rate'=>$store_rebate,
                    'rebate_money'=>$storeMoney,
                    'rebate_date'=>$date,
                    'rebate_cost'=>$info['cost'],
                    'number'=>$storeWhereCount,
                    'create_time'=>$date,
                    'update_time'=>$date
                ];

                if(!Rebate::create($insertData)){
                    throw new Exception('确认失败');
                }

                $merchantId = $storeInfo['merchant_id'];
                $result = StoreAccountManager::money($merchantId,$info['store_id'],$storeMoney,StoreAccountManager::CHANGE_TYPE_INCOME,$date,StoreAccountManager::TYPE_TEAM,[],false);
                if ($result['code']!=StoreAccountManager::$successCode){
                    throw new Exception($result['message']);
                }

                $statisticsResult = StatisticsManager::enter($merchantId,$info['store_id'],$storeMoney,time(),ProfitStatistics::TYPE_TEAM,StatisticsManager::TYPE_PROFIT,false);
                if ($statisticsResult['code']!=StatisticsManager::$successCode){
                    throw new Exception($statisticsResult['message']);
                }

            }else{
                $captain_rebate = $level['captain_rebate'];
                $money = bcdiv(bcmul(bcmul($info['cost'],$storeWhereMoney,2),$captain_rebate,2),100,2);
                $consumeTotal = bcadd($consumeTotal,$money,2);
                $insertData  = [
                    'user_id'=>$info['captain'],
                    'store_id'=>$info['store_id'],
                    'type'=>Rebate::TYPE_TEAM,
                    'relation_id'=>$info['t_id'],
                    'rebate_rate'=>$captain_rebate,
                    'rebate_money'=>$money,
                    'rebate_date'=>$date,
                    'rebate_cost'=>$info['cost'],
                    'number'=>$storeWhereMoney,
                    'create_time'=>$date,
                    'update_time'=>$date
                ];

                if(!Rebate::create($insertData)){
                    throw new Exception('确认失败');
                }

                $result = UserAccountManager::money($info['captain'],$money,UserAccountManager::CHANGE_TYPE_INCOME,$date,UserAccountManager::TYPE_TEAM,[$info['t_id']],false);
                if ($result['code']!=UserAccountManager::$successCode){
                    throw new Exception($result['message']);
                }
            }


            $proxyInfo = Proxy::where('province',$info['province'])->where('city',$info['city'])->find();
            if ($proxyInfo){
                $proxyRate = $proxyInfo['rate'] ?? $level['proxy_rebate'];
                $proxyMoney = bcdiv(bcmul($proxyWhereMoney,$proxyRate,2),100,2);

                $consumeTotal = bcadd($consumeTotal,$proxyMoney,2);
                $insertData  = [
                    'user_id'=>$proxyInfo['user_id'],
                    'store_id'=>$info['store_id'],
                    'type'=>Rebate::TYPE_TEAM,
                    'relation_id'=>$info['t_id'],
                    'rebate_rate'=>$proxyRate,
                    'rebate_money'=>$proxyMoney,
                    'rebate_date'=>$date,
                    'rebate_cost'=>$info['cost'],
                    'number'=>$proxyWhereCount,
                    'create_time'=>$date,
                    'update_time'=>$date
                ];

                if(!Rebate::create($insertData)){
                    throw new Exception('确认失败');
                }

                $result = UserAccountManager::money($proxyInfo['user_id'],$proxyMoney,UserAccountManager::CHANGE_TYPE_INCOME,$date,UserAccountManager::TYPE_PROXY_STORE_TEAM_REWARD,['relation_id'=>$info['t_id']],false);
                if ($result['code']!=UserAccountManager::$successCode){
                    throw new Exception($result['message']);
                }

                $resultPlatform = PlatformManager::platformLog($proxyMoney,date('Y-m-d H:i:s',$date),Log::DIRECTIVE_OUT,Log::TYPE_PROXY_STORE_TEAM_REWARD,['recipient'=>$proxyInfo['user_id']],false);
                if ($resultPlatform['code']!=PlatformManager::$successCode){
                    throw new Exception($resultPlatform['message']);
                }

                $resultProxy = ProxyManager::Statistics($proxyMoney,date('Y-m-d H:i:s',$date),$proxyInfo['user_id'],$proxyInfo['id'],false);
                if ($resultProxy['code']!=ProxyManager::$successCode){
                    throw new Exception($resultProxy['message']);
                }
            }

            if ($consumeTotal){
                $surplusAmount = bcsub($totalMoney,$consumeTotal,2);
                if ($surplusAmount){
                    $resultPlatform = PlatformManager::platformLog($surplusAmount,date('Y-m-d H:i:s',$date),Log::DIRECTIVE_INCOME,Log::TYPE_TEAM,[],false);
                    if ($resultPlatform['code']!=PlatformManager::$successCode){
                        throw new Exception($resultPlatform['message']);
                    }
                }
            }
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans){
                Db::rollback();
            }
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage()];


    }


}